package com.study.server.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.study.server.domain.Section;
import com.study.server.domain.SectionExample;
import com.study.server.dto.SectionDto;
import com.study.server.dto.PageDto;
import com.study.server.mapper.SectionMapper;
import com.study.server.util.CopyUtil;
import com.study.server.util.UuidUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class SectionService {

    @Resource
   private SectionMapper mapper;


    public String queryAll(){
        return "";
    };

    /**
     * 查询操作
     * @param sectionPageDto
     */
    public void list(PageDto<Section> sectionPageDto){

        Page<Object> objects = PageHelper.startPage(sectionPageDto.getPage(),sectionPageDto.getSize());
        SectionExample sectionExample = new SectionExample();
        //      sectionExample.createCriteria().andIdEqualTo("1");
    //   sectionExample.setOrderByClause("id desc");
        List<Section> sectionList = mapper.selectByExample(sectionExample);

        PageInfo<Section> sectionPageInfo = new PageInfo<>(sectionList);
        sectionPageDto.setTotal(sectionPageInfo.getTotal());
        List<SectionDto> sectionDtoList = new ArrayList<SectionDto>();
        for (int i = 0; i <sectionList.size() ; i++) {
            Section section = sectionList.get(i);
            SectionDto dto = new SectionDto();
            BeanUtils.copyProperties(section,dto);
            sectionDtoList.add(dto);
        }
        sectionPageDto.setList(sectionList);

    };

    /**
     * 删除或新增
     * @param sectionDto
     */

    public void save(SectionDto sectionDto){
        Section section  = CopyUtil.copy(sectionDto,Section.class);
        if(StringUtils.isEmpty(section.getId())){
          this.insert(section);
      }else {
            this.update(section);
      }
    }

    /**
     * 新增
     * @param section
     */

    private void insert(Section section){
        section.setId(UuidUtil.getShortUuid());
        mapper.insert( section );
    }
    private void update(Section section){
        mapper.updateByPrimaryKey(section);
    }

    /**
     * 删除
     * @param id
     */
    public void del(String id){
        mapper.deleteByPrimaryKey(id);
    }

}
